package com.tanhua.dubbo.api;

import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class CommentApiImpl implements CommentApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    //根据动态id和互动类型，分页查询数据
    public List<Comment> findComments(Integer page, Integer pagesize, Integer commentType, String movementId) {
        Criteria criteria = Criteria.where("publishId").is(new ObjectId(movementId))
                .and("commentType").is(commentType);
        Query query = Query.query(criteria)
                .with(Sort.by(Sort.Order.desc("created")))
                .skip((page - 1) * pagesize)
                .limit(pagesize);
        return mongoTemplate.find(query, Comment.class);
    }

    //保存互动数据
    public Integer save(Comment comment, Integer type) {
        if (type != 1) { //处理动态
            //1.根据动态id，查询动态
            ObjectId movementId = comment.getPublishId();
            Movement movement = mongoTemplate.findById(movementId, Movement.class);
            //2.设置comment中的动态发布人publishUserId
            comment.setPublishUserId(movement.getUserId());
            //3.保存Comment到数据库中
            mongoTemplate.save(comment);
//        //4.跟更新动态表中的评论数量
//        Criteria criteria = Criteria.where("id").is(movementId);//查询条件，需要更新的动态
//        Query query = Query.query(criteria);
//        Update update = new Update();
//        update.inc("commentCount", 1);//对指定的字段，增加相应的数值
//        mongoTemplate.updateFirst(query, update, Movement.class);//updateFirst方法的三个参数，
//        //5.获取总评论
//        Movement movement1 = mongoTemplate.findById(movementId, Movement.class);
//        Integer count = movement1.getCommentCount();

            //更新并获取，更新之后，最新的数据
            Criteria criteria = Criteria.where("id").is(movementId);//查询条件，需要更新的动态
            Query query = Query.query(criteria);
            Update update = new Update();
            //对更新的字段进行判断，进行更新
            if (comment.getCommentType() == 1) {
                update.inc("likeCount", 1);//对指定的字段，增加相应的数值
            } else if (comment.getCommentType() == 2) {
                update.inc("commentCount", 1);//对指定的字段，增加相应的数值
            } else {
                update.inc("loveCount", 1);//对指定的字段，增加相应的数值
            }
            //更新配置对象
            FindAndModifyOptions options = new FindAndModifyOptions();
            options.returnNew(true);//设置更新之后，返回最新记录
            Movement modify = mongoTemplate.findAndModify(query, update, options, Movement.class);//四个参数，查询条件query，更新对象update，更新配置，实体类.class
            //返回更新后的数量
            if (comment.getCommentType() == 1) {
                return modify.getLikeCount();
            } else if (comment.getCommentType() == 2) {
                return modify.getCommentCount();
            } else {
                return modify.getLoveCount();
            }
        } else { //设置视屏
            //1.根据动态id，查询视频
            ObjectId videoId = comment.getPublishId();
            Video video = mongoTemplate.findById(videoId, Video.class);
            //2.设置comment中的动态发布人publishUserId
            comment.setPublishUserId(video.getUserId());
            //3.保存Comment到数据库中
            mongoTemplate.save(comment);
            //更新并获取，更新之后，最新的数据
            Criteria criteria = Criteria.where("id").is(videoId);//查询条件，需要更新的视频
            Query query = Query.query(criteria);
            Update update = new Update();
            //对更新的字段进行判断，进行更新
            if (comment.getCommentType() == 1) {
                update.inc("likeCount", 1);//对指定的字段，增加相应的数值
            } else if (comment.getCommentType() == 2) {
                update.inc("commentCount", 1);//对指定的字段，增加相应的数值
            } /*else {
                update.inc("loveCount", 1);//对指定的字段，增加相应的数值
            }*/
            //更新配置对象
            FindAndModifyOptions options = new FindAndModifyOptions();
            options.returnNew(true);//设置更新之后，返回最新记录
            Video modify = mongoTemplate.findAndModify(query, update, options, Video.class);//四个参数，查询条件query，更新对象update，更新配置，实体类.class
            //返回更新后的数量
            if (comment.getCommentType() == 1) {
                return modify.getLikeCount();
            } else {
                return modify.getCommentCount();
            } /*else {
                return modify.getLoveCount();
            }*/
        }
    }

    //判断互动是否存在
    public Boolean hasComment(String movementId, Long userId, Integer commentType) {
        Criteria criteria = Criteria.where("publishId").is(new ObjectId(movementId))
                .and("userId").is(userId)
                .and("commentType").is(commentType);
        Query query = Query.query(criteria);
        //获取数据是否存在（true--存在，false--不存在）
        return mongoTemplate.exists(query, Comment.class);
    }

    //删除互动数据
    public Integer delete(String movementId, Long userId, Integer commentType, Integer type) {
        //1.删除互动表Comment中的数据
        Criteria commentCriteria = Criteria.where("publishId").is(new ObjectId(movementId))
                .and("userId").is(userId)
                .and("commentType").is(commentType);
        Query commentQuery = Query.query(commentCriteria);
        mongoTemplate.remove(commentQuery, Comment.class);

        //判断是视屏还是动态
        if (type != 1) {
            //2.更新动态表中互动总数（点赞，评论，喜欢）  update movement set likeCount = likeCount -1 where id=?
            //查询条件
            Criteria criteria = Criteria.where("id").is(movementId);
            Query query = Query.query(criteria);
            //更新字段
            Update update = new Update();
            if (commentType == 1) {
                update.inc("likeCount", -1);
            } else if (commentType == 2) {
                update.inc("commentCount", -1);
            } else {
                update.inc("loveCount", -1);
            }
            //更新的配置
            FindAndModifyOptions options = new FindAndModifyOptions();
            options.returnNew(true);
            Movement modify = mongoTemplate.findAndModify(query, update, options, Movement.class);
            //3.返回互动总数（点赞，评论，喜欢）
            if (commentType == 1) {
                return modify.getLikeCount();
            } else if (commentType == 2) {
                return modify.getCommentCount();
            } else {
                return modify.getLoveCount();
            }
        } else {
            //2.更新动态表中互动总数（点赞，评论，喜欢）  update movement set likeCount = likeCount -1 where id=?
            //查询条件
            Criteria criteria = Criteria.where("id").is(movementId);
            Query query = Query.query(criteria);
            //更新字段
            Update update = new Update();
            if (commentType == 1) {
                update.inc("likeCount", -1);
            } else if (commentType == 2) {
                update.inc("commentCount", -1);
            }/* else {
                update.inc("loveCount", -1);
            }*/
            //更新的配置
            FindAndModifyOptions options = new FindAndModifyOptions();
            options.returnNew(true);
            Video modify = mongoTemplate.findAndModify(query, update, options, Video.class);
            //3.返回互动总数（点赞，评论，喜欢）
            if (commentType == 1) {
                return modify.getLikeCount();
            } else if (commentType == 2) {
                return modify.getCommentCount();
            } /*else {
                return modify.getLoveCount();
            }*/
        }
        return null;
    }

    @Override
    public PageResult findMovComments(Integer page, Integer pagesize, Integer commentType, String messageId) {
        Criteria criteria = Criteria.where("publishId").is(new ObjectId(messageId))
                .and("commentType").is(commentType);
        Query query = Query.query(criteria);
        long count = mongoTemplate.count(query, Comment.class);
        query.with(Sort.by(Sort.Order.desc("created")))
                .skip((page - 1) * pagesize)
                .limit(pagesize);
        List<Comment> list = mongoTemplate.find(query, Comment.class);
        return new PageResult(page, pagesize, count, list);
    }
}
